from django.db.models import Q
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet

from goods.models import SKUImage, SKU, SPU, SPUSpecification
from meiduo_admin.serializers.skus import SKUImageSerializer, SKUSimpleSerializer, SKUSerializer, SPUSimpleSerializer, \
    SPUSpecSerializer
from orders.models import OrderInfo


class SKUImageViewSet(ModelViewSet):
    permission_classes = [IsAdminUser]

    lookup_value_regex = '\d+'

    queryset = SKUImage.objects.all()
    serializer_class = SKUImageSerializer


class SKUSimpleView(ListAPIView):
    permission_classes = [IsAdminUser]

    queryset = SKU.objects.all()
    serializer_class = SKUSimpleSerializer

    pagination_class = None


class SKUViewSet(ModelViewSet):
    """sku管理"""
    permission_classes = [IsAdminUser]

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            skus = SKU.objects.filter(Q(name__contains=keyword) | Q(caption__contains=keyword))
        else:
            skus = SKU.objects.all()
        return skus

    serializer_class = SKUSerializer


# GET /meiduo_admin/goods/simple/
class SPUSimpleView(ListAPIView):
    permission_classes = [IsAdminUser]

    serializer_class = SPUSimpleSerializer
    queryset = SPU.objects.all()

    # 关闭分页
    pagination_class = None


# GET /meiduo_admin/goods/(?P<pk>\d+)/specs/
class SPUSpecView(ListAPIView):
    permission_classes = [IsAdminUser]

    serializer_class = SPUSpecSerializer
    # queryset = SPUSpecification.objects.filter(spu_id=pk)

    def get_queryset(self):
        """
        self.kwargs: 字典，保存了从url地址中提取所有命名参数
        """
        pk = self.kwargs['pk']
        return SPUSpecification.objects.filter(spu_id=pk)

    # 关闭分页
    pagination_class = None
